package eerbaar.action.internal.lib.position;

import eerbaar.area.IArea;
import eerbaar.area.SquareIterator;
import eerbaar.elements.IElement;
import eerbaar.game.IGame;
import eerbaar.position.IPosition;
import eerbaar.position.PositionFactory;

public class CenterPositionGenerator implements IPositionGenerator {

    private SquareIterator iterator;

    private void init(IArea area) {

        if (this.iterator != null) {
            return;
        }

        int y = area.getHeight() / 2;
        int x = area.getWidth() / 2;
        IPosition start = PositionFactory.createPosition(x, y);
        this.iterator = new SquareIterator(start, 3, true);
    }

    @Override
    public IPosition next(IGame game) {

        IPosition result = null;

        IArea area = game.getArea();
        init(area);

        IPosition p;
        while ((p = iterator.next()) != null) {

            IElement[] elements = area.getElements(p);
            if (elements.length > 0) {
                continue;
            }

            result = p;
            break;
        }

        return result;
    }
}
